package com.woniu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.dto.TaskDto;
import com.woniu.entity.ChargingStation;
import com.woniu.mapper.ChargingStationMapper;
import com.woniu.util.ParseDateUtil;
import com.woniu.util.ResponseData;
import com.woniu.util.easyExcelUtil.EasyExcelUtil;
import com.woniu.vo.AlaramSettingVo;
import com.woniu.vo.TaskExcelVo;
import com.woniu.vo.TaskVo;
import com.woniu.entity.Task;
import com.woniu.service.TaskService;
import com.woniu.mapper.TaskMapper;
import com.woniu.util.CodeGeneratorUtil;
import com.woniu.util.PageData;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author Apricity
 * @description 针对表【task(任务表)】的数据库操作Service实现
 * @createDate 2025-02-13 20:16:59
 */
@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task>
        implements TaskService {

    @Resource
    private TaskMapper taskMapper;
    @Resource
    private ChargingStationMapper chargingStationMapper;

    @Override
    public void addTask(TaskDto task) {
        Task taskAdd = new Task();

        BeanUtils.copyProperties(task, taskAdd);

        String stationName = task.getStationName();

        ChargingStation chargingStation = chargingStationMapper.selectOne(new QueryWrapper<ChargingStation>().eq("station_name", stationName));
        Long stationId = chargingStation.getId();

        taskAdd.setStationId(stationId);
        String taskNumber = CodeGeneratorUtil.generateTaskCode();
        taskAdd.setTaskNumber(taskNumber);
        taskAdd.setTaskStatus(CodeGeneratorUtil.PENDING_PROCESSING);

        taskMapper.insert(taskAdd);
    }

    @Override
    public void updateTask(Map<String, Object> taskMap) {
        Task task = new Task();
        if (taskMap.containsKey("id")) {
            Integer id = (Integer) taskMap.get("id");
            task.setId(id.longValue());
        }
        if (taskMap.containsKey("taskName")) {
            task.setTaskName((String) taskMap.get("taskName"));
        }
        if (taskMap.containsKey("taskNumber")) {
            task.setTaskNumber((String) taskMap.get("taskNumber"));
        }
        if (taskMap.containsKey("userId")) {
            Integer userId = (Integer) taskMap.get("userId");
            task.setMaintenancePersonId(userId.longValue());
        }
        if (taskMap.containsKey("workCycle")) {
            task.setWorkCycle((String) taskMap.get("workCycle"));
        }
        if (taskMap.containsKey("taskType")) {
            task.setTaskType((String) taskMap.get("taskType"));
        }
        // 时间
        if (taskMap.containsKey("plannedStartTime")) {
            String plannedStartTimeStr = (String) taskMap.get("plannedStartTime");
            if (plannedStartTimeStr == null || plannedStartTimeStr.trim().isEmpty()) {
                return; // 直接跳过赋值，继续执行后面的逻辑
            }
            try {
                DateTimeFormatter formatter;

                // 判断时间格式，如果不包含空格，说明是 "yyyy-MM-dd"
                if (plannedStartTimeStr.length() == 10) {
                    formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    LocalDate localDate = LocalDate.parse(plannedStartTimeStr, formatter);
                    // 转换为 Date 类型
                    Date plannedStartTime = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
                    task.setPlannedStartTime(plannedStartTime);
                } else {
                    formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    LocalDateTime localDateTime = LocalDateTime.parse(plannedStartTimeStr, formatter);
                    // 转换为 Date 类型
                    Date plannedStartTime = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
                    task.setPlannedStartTime(plannedStartTime);
                }
            } catch (Exception e) {
                e.printStackTrace(); // 处理日期解析异常
            }
        }

        if (taskMap.containsKey("plannedEndTime")) {
            String plannedEndTimeStr = (String) taskMap.get("plannedEndTime");
            if (plannedEndTimeStr == null || plannedEndTimeStr.trim().isEmpty()) {
                return; // 直接跳过赋值，继续执行后面的逻辑
            }
            try {
                DateTimeFormatter formatter;

                // 判断时间格式，如果不包含空格，说明是 "yyyy-MM-dd"
                if (plannedEndTimeStr.length() == 10) {
                    formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    LocalDate localDate = LocalDate.parse(plannedEndTimeStr, formatter);
                    // 转换为 Date 类型
                    Date plannedEndTime = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
                    task.setPlannedEndTime(plannedEndTime);
                } else {
                    formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    LocalDateTime localDateTime = LocalDateTime.parse(plannedEndTimeStr, formatter);
                    // 转换为 Date 类型
                    Date plannedStartTime = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
                    task.setPlannedEndTime(plannedStartTime);
                }
            } catch (Exception e) {
                e.printStackTrace(); // 处理日期解析异常
            }
        }

        // 处理时间字段
        task.setPlannedStartTime(ParseDateUtil.parseDate(taskMap, "plannedStartTime"));
        task.setPlannedEndTime(ParseDateUtil.parseDate(taskMap, "plannedEndTime"));
        task.setActualStartTime(ParseDateUtil.parseDate(taskMap, "actualStartTime"));
        task.setActualEndTime(ParseDateUtil.parseDate(taskMap, "actualEndTime"));

        /*if (taskMap.containsKey("taskStatus")) {
            task.setTaskStatus((String) taskMap.get("taskStatus"));
        }*/
        task.setTaskStatus(CodeGeneratorUtil.TASK_STATUS);

        if (taskMap.containsKey("taskDescription")) {
            task.setTaskDescription((String) taskMap.get("taskDescription"));
        }
        if (taskMap.containsKey("handlingDescription")) {
            task.setHandlingDescription((String) taskMap.get("handlingDescription"));
        }
        taskMapper.updateById(task);
    }

    @Override
    public Page<TaskVo> pageTask(PageData pageData) {
        Page<TaskVo> taskDtoPage = new Page<>(pageData.getPageNum(), pageData.getPageSize());
        IPage<TaskVo> records = taskMapper.pageTaskList(taskDtoPage, (String) pageData.getParam());
        return (Page<TaskVo>) records;
    }

    @Override
    public TaskVo queryById(String taskNumber) {
        TaskVo taskVo = taskMapper.queryById(taskNumber);

        return taskVo;
    }

    @Override
    public ResponseData<?> toTaskExcel(HttpServletResponse response) throws IOException {
        String fileName = "任务表";

        ArrayList<TaskExcelVo> taskVos = getTaskVo();

        // **设置 Excel 响应头**
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="
                + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");

        EasyExcelUtil.writeWithSheetsWeb(response,fileName)
                .writeModel(TaskExcelVo.class, taskVos,"taskSheet")
                .finish();

        return ResponseData.ok();
    }

    private ArrayList<TaskExcelVo> getTaskVo() {
        ArrayList<TaskExcelVo> list = new ArrayList<>();

        List<TaskVo> vo = taskMapper.excelTaskVo();

        for (TaskVo taskVo : vo) {
            TaskExcelVo tkVo = new TaskExcelVo();
            BeanUtils.copyProperties(taskVo, tkVo);

            list.add(tkVo);
        }


        return list;
    }
}




